home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Objects / listobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  36.1 KB  |  1,523 lines

  1. /* List object implementation */
  2.  
  3. #include "Python.h"
  4. #include "protos/listobject.h"
  5.  
  6. #ifdef STDC_HEADERS
  7. #include <stddef.h>
  8. #else
  9. #include <sys/types.h>        /* For size_t */
  10. #endif
  11.  
  12. #define ROUNDUP(n, PyTryBlock) \
  13.     ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
  14.  
  15. static int
  16. roundupsize(n)
  17.     int n;
  18. {
  19.     if (n < 500)
  20.         return ROUNDUP(n, 10);
  21.     else
  22.         return ROUNDUP(n, 100);
  23. }
  24.  
  25. #define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
  26.  
  27. PyObject *
  28. PyList_New(size)
  29.     int size;
  30. {
  31.     int i;
  32.     PyListObject *op;
  33.     size_t nbytes;
  34.     if (size < 0) {
  35.         PyErr_BadInternalCall();
  36.         return NULL;
  37.     }
  38.     nbytes = size * sizeof(PyObject *);
  39.     /* Check for overflow */
  40.     if (nbytes / sizeof(PyObject *) != (size_t)size) {
  41.         return PyErr_NoMemory();
  42.     }
  43.     /* PyObject_NewVar is inlined */
  44.     op = (PyListObject *) PyObject_MALLOC(sizeof(PyListObject));
  45.     if (op == NULL) {
  46.         return PyErr_NoMemory();
  47.     }
  48.     if (size <= 0) {
  49.         op->ob_item = NULL;
  50.     }
  51.     else {
  52.         op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
  53.         if (op->ob_item == NULL) {
  54.             PyObject_FREE(op);
  55.             return PyErr_NoMemory();
  56.         }
  57.     }
  58.     PyObject_INIT_VAR(op, &PyList_Type, size);
  59.     for (i = 0; i < size; i++)
  60.         op->ob_item[i] = NULL;
  61.     return (PyObject *) op;
  62. }
  63.  
  64. int
  65. PyList_Size(op)
  66.     PyObject *op;
  67. {
  68.     if (!PyList_Check(op)) {
  69.         PyErr_BadInternalCall();
  70.         return -1;
  71.     }
  72.     else
  73.         return ((PyListObject *)op) -> ob_size;
  74. }
  75.  
  76. static PyObject *indexerr;
  77.  
  78. PyObject *
  79. PyList_GetItem(op, i)
  80.     PyObject *op;
  81.     int i;
  82. {
  83.     if (!PyList_Check(op)) {
  84.         PyErr_BadInternalCall();
  85.         return NULL;
  86.     }
  87.     if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  88.         if (indexerr == NULL)
  89.             indexerr = PyString_FromString(
  90.                 "list index out of range");
  91.         PyErr_SetObject(PyExc_IndexError, indexerr);
  92.         return NULL;
  93.     }
  94.     return ((PyListObject *)op) -> ob_item[i];
  95. }
  96.  
  97. int
  98. PyList_SetItem(op, i, newitem)
  99.     register PyObject *op;
  100.     register int i;
  101.     register PyObject *newitem;
  102. {
  103.     register PyObject *olditem;
  104.     register PyObject **p;
  105.     if (!PyList_Check(op)) {
  106.         Py_XDECREF(newitem);
  107.         PyErr_BadInternalCall();
  108.         return -1;
  109.     }
  110.     if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  111.         Py_XDECREF(newitem);
  112.         PyErr_SetString(PyExc_IndexError,
  113.                 "list assignment index out of range");
  114.         return -1;
  115.     }
  116.     p = ((PyListObject *)op) -> ob_item + i;
  117.     olditem = *p;
  118.     *p = newitem;
  119.     Py_XDECREF(olditem);
  120.     return 0;
  121. }
  122.  
  123. static int
  124. ins1(self, where, v)
  125.     PyListObject *self;
  126.     int where;
  127.     PyObject *v;
  128. {
  129.     int i;
  130.     PyObject **items;
  131.     if (v == NULL) {
  132.         PyErr_BadInternalCall();
  133.         return -1;
  134.     }
  135.     items = self->ob_item;
  136.     NRESIZE(items, PyObject *, self->ob_size+1);
  137.     if (items == NULL) {
  138.         PyErr_NoMemory();
  139.         return -1;
  140.     }
  141.     if (where < 0)
  142.         where = 0;
  143.     if (where > self->ob_size)
  144.         where = self->ob_size;
  145.     for (i = self->ob_size; --i >= where; )
  146.         items[i+1] = items[i];
  147.     Py_INCREF(v);
  148.     items[where] = v;
  149.     self->ob_item = items;
  150.     self->ob_size++;
  151.     return 0;
  152. }
  153.  
  154. int
  155. PyList_Insert(op, where, newitem)
  156.     PyObject *op;
  157.     int where;
  158.     PyObject *newitem;
  159. {
  160.     if (!PyList_Check(op)) {
  161.         PyErr_BadInternalCall();
  162.         return -1;
  163.     }
  164.     return ins1((PyListObject *)op, where, newitem);
  165. }
  166.  
  167. int
  168. PyList_Append(op, newitem)
  169.     PyObject *op;
  170.     PyObject *newitem;
  171. {
  172.     if (!PyList_Check(op)) {
  173.         PyErr_BadInternalCall();
  174.         return -1;
  175.     }
  176.     return ins1((PyListObject *)op,
  177.         (int) ((PyListObject *)op)->ob_size, newitem);
  178. }
  179.  
  180. /* Methods */
  181.  
  182. static void
  183. list_dealloc(op)
  184.     PyListObject *op;
  185. {
  186.     int i;
  187.     Py_TRASHCAN_SAFE_BEGIN(op)
  188.     if (op->ob_item != NULL) {
  189.         /* Do it backwards, for Christian Tismer.
  190.            There's a simple test case where somehow this reduces
  191.            thrashing when a *very* large list is created and
  192.            immediately deleted. */
  193.         i = op->ob_size;
  194.         while (--i >= 0) {
  195.             Py_XDECREF(op->ob_item[i]);
  196.         }
  197.         PyMem_FREE(op->ob_item);
  198.     }
  199.     PyObject_DEL(op);
  200.     Py_TRASHCAN_SAFE_END(op)
  201. }
  202.  
  203. static int
  204. list_print(op, fp, flags)
  205.     PyListObject *op;
  206.     FILE *fp;
  207.     int flags;
  208. {
  209.     int i;
  210.  
  211.     i = Py_ReprEnter((PyObject*)op);
  212.     if (i != 0) {
  213.         if (i < 0)
  214.             return i;
  215.         fprintf(fp, "[...]");
  216.         return 0;
  217.     }
  218.     fprintf(fp, "[");
  219.     for (i = 0; i < op->ob_size; i++) {
  220.         if (i > 0)
  221.             fprintf(fp, ", ");
  222.         if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
  223.             Py_ReprLeave((PyObject *)op);
  224.             return -1;
  225.         }
  226.     }
  227.     fprintf(fp, "]");
  228.     Py_ReprLeave((PyObject *)op);
  229.     return 0;
  230. }
  231.  
  232. static PyObject *
  233. list_repr(v)
  234.     PyListObject *v;
  235. {
  236.     PyObject *s, *comma;
  237.     int i;
  238.  
  239.     i = Py_ReprEnter((PyObject*)v);
  240.     if (i != 0) {
  241.         if (i > 0)
  242.             return PyString_FromString("[...]");
  243.         return NULL;
  244.     }
  245.     s = PyString_FromString("[");
  246.     comma = PyString_FromString(", ");
  247.     for (i = 0; i < v->ob_size && s != NULL; i++) {
  248.         if (i > 0)
  249.             PyString_Concat(&s, comma);
  250.         PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
  251.     }
  252.     Py_XDECREF(comma);
  253.     PyString_ConcatAndDel(&s, PyString_FromString("]"));
  254.     Py_ReprLeave((PyObject *)v);
  255.     return s;
  256. }
  257.  
  258. static int
  259. list_compare(v, w)
  260.     PyListObject *v, *w;
  261. {
  262.     int i;
  263.     for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
  264.         int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
  265.         if (cmp != 0)
  266.             return cmp;
  267.     }
  268.     return v->ob_size - w->ob_size;
  269. }
  270.  
  271. static int
  272. list_length(a)
  273.     PyListObject *a;
  274. {
  275.     return a->ob_size;
  276. }
  277.  
  278.  
  279.  
  280. static int
  281. list_contains(a, el)
  282.     PyListObject *a;
  283.     PyObject *el;
  284. {
  285.     int i, cmp;
  286.  
  287.     for (i = 0; i < a->ob_size; ++i) {
  288.         cmp = PyObject_Compare(el, PyList_GET_ITEM(a, i));
  289.         if (cmp == 0)
  290.             return 1;
  291.         if (PyErr_Occurred())
  292.             return -1;
  293.     }
  294.     return 0;
  295. }
  296.  
  297.  
  298. static PyObject *
  299. list_item(a, i)
  300.     PyListObject *a;
  301.     int i;
  302. {
  303.     if (i < 0 || i >= a->ob_size) {
  304.         if (indexerr == NULL)
  305.             indexerr = PyString_FromString(
  306.                 "list index out of range");
  307.         PyErr_SetObject(PyExc_IndexError, indexerr);
  308.         return NULL;
  309.     }
  310.     Py_INCREF(a->ob_item[i]);
  311.     return a->ob_item[i];
  312. }
  313.  
  314. static PyObject *
  315. list_slice(a, ilow, ihigh)
  316.     PyListObject *a;
  317.     int ilow, ihigh;
  318. {
  319.     PyListObject *np;
  320.     int i;
  321.     if (ilow < 0)
  322.         ilow = 0;
  323.     else if (ilow > a->ob_size)
  324.         ilow = a->ob_size;
  325.     if (ihigh < ilow)
  326.         ihigh = ilow;
  327.     else if (ihigh > a->ob_size)
  328.         ihigh = a->ob_size;
  329.     np = (PyListObject *) PyList_New(ihigh - ilow);
  330.     if (np == NULL)
  331.         return NULL;
  332.     for (i = ilow; i < ihigh; i++) {
  333.         PyObject *v = a->ob_item[i];
  334.         Py_INCREF(v);
  335.         np->ob_item[i - ilow] = v;
  336.     }
  337.     return (PyObject *)np;
  338. }
  339.  
  340. PyObject *
  341. PyList_GetSlice(a, ilow, ihigh)
  342.     PyObject *a;
  343.     int ilow, ihigh;
  344. {
  345.     if (!PyList_Check(a)) {
  346.         PyErr_BadInternalCall();
  347.         return NULL;
  348.     }
  349.     return list_slice((PyListObject *)a, ilow, ihigh);
  350. }
  351.  
  352. static PyObject *
  353. list_concat(a, bb)
  354.     PyListObject *a;
  355.     PyObject *bb;
  356. {
  357.     int size;
  358.     int i;
  359.     PyListObject *np;
  360.     if (!PyList_Check(bb)) {
  361.         PyErr_BadArgument();
  362.         return NULL;
  363.     }
  364. #define b ((PyListObject *)bb)
  365.     size = a->ob_size + b->ob_size;
  366.     np = (PyListObject *) PyList_New(size);
  367.     if (np == NULL) {
  368.         return NULL;
  369.     }
  370.     for (i = 0; i < a->ob_size; i++) {
  371.         PyObject *v = a->ob_item[i];
  372.         Py_INCREF(v);
  373.         np->ob_item[i] = v;
  374.     }
  375.     for (i = 0; i < b->ob_size; i++) {
  376.         PyObject *v = b->ob_item[i];
  377.         Py_INCREF(v);
  378.         np->ob_item[i + a->ob_size] = v;
  379.     }
  380.     return (PyObject *)np;
  381. #undef b
  382. }
  383.  
  384. static PyObject *
  385. list_repeat(a, n)
  386.     PyListObject *a;
  387.     int n;
  388. {
  389.     int i, j;
  390.     int size;
  391.     PyListObject *np;
  392.     PyObject **p;
  393.     if (n < 0)
  394.         n = 0;
  395.     size = a->ob_size * n;
  396.     np = (PyListObject *) PyList_New(size);
  397.     if (np == NULL)
  398.         return NULL;
  399.     p = np->ob_item;
  400.     for (i = 0; i < n; i++) {
  401.         for (j = 0; j < a->ob_size; j++) {
  402.             *p = a->ob_item[j];
  403.             Py_INCREF(*p);
  404.             p++;
  405.         }
  406.     }
  407.     return (PyObject *) np;
  408. }
  409.  
  410. static int
  411. list_ass_slice(a, ilow, ihigh, v)
  412.     PyListObject *a;
  413.     int ilow, ihigh;
  414.     PyObject *v;
  415. {
  416.     /* Because [X]DECREF can recursively invoke list operations on
  417.        this list, we must postpone all [X]DECREF activity until
  418.        after the list is back in its canonical shape.  Therefore
  419.        we must allocate an additional array, 'recycle', into which
  420.        we temporarily copy the items that are deleted from the
  421.        list. :-( */
  422.     PyObject **recycle, **p;
  423.     PyObject **item;
  424.     int n; /* Size of replacement list */
  425.     int d; /* Change in size */
  426.     int k; /* Loop index */
  427. #define b ((PyListObject *)v)
  428.     if (v == NULL)
  429.         n = 0;
  430.     else if (PyList_Check(v)) {
  431.         n = b->ob_size;
  432.         if (a == b) {
  433.             /* Special case "a[i:j] = a" -- copy b first */
  434.             int ret;
  435.             v = list_slice(b, 0, n);
  436.             ret = list_ass_slice(a, ilow, ihigh, v);
  437.             Py_DECREF(v);
  438.             return ret;
  439.         }
  440.     }
  441.     else {
  442.         PyErr_BadArgument();
  443.         return -1;
  444.     }
  445.     if (ilow < 0)
  446.         ilow = 0;
  447.     else if (ilow > a->ob_size)
  448.         ilow = a->ob_size;
  449.     if (ihigh < ilow)
  450.         ihigh = ilow;
  451.     else if (ihigh > a->ob_size)
  452.         ihigh = a->ob_size;
  453.     item = a->ob_item;
  454.     d = n - (ihigh-ilow);
  455.     if (ihigh > ilow)
  456.         p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
  457.     else
  458.         p = recycle = NULL;
  459.     if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
  460.         for (k = ilow; k < ihigh; k++)
  461.             *p++ = item[k];
  462.         if (d < 0) {
  463.             for (/*k = ihigh*/; k < a->ob_size; k++)
  464.                 item[k+d] = item[k];
  465.             a->ob_size += d;
  466.             NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
  467.             a->ob_item = item;
  468.         }
  469.     }
  470.     else { /* Insert d items; recycle ihigh-ilow items */
  471.         NRESIZE(item, PyObject *, a->ob_size + d);
  472.         if (item == NULL) {
  473.             if (recycle != NULL)
  474.                 PyMem_DEL(recycle);
  475.             PyErr_NoMemory();
  476.             return -1;
  477.         }
  478.         for (k = a->ob_size; --k >= ihigh; )
  479.             item[k+d] = item[k];
  480.         for (/*k = ihigh-1*/; k >= ilow; --k)
  481.             *p++ = item[k];
  482.         a->ob_item = item;
  483.         a->ob_size += d;
  484.     }
  485.     for (k = 0; k < n; k++, ilow++) {
  486.         PyObject *w = b->ob_item[k];
  487.         Py_XINCREF(w);
  488.         item[ilow] = w;
  489.     }
  490.     if (recycle) {
  491.         while (--p >= recycle)
  492.             Py_XDECREF(*p);
  493.         PyMem_DEL(recycle);
  494.     }
  495.     return 0;
  496. #undef b
  497. }
  498.  
  499. int
  500. PyList_SetSlice(a, ilow, ihigh, v)
  501.     PyObject *a;
  502.     int ilow, ihigh;
  503.     PyObject *v;
  504. {
  505.     if (!PyList_Check(a)) {
  506.         PyErr_BadInternalCall();
  507.         return -1;
  508.     }
  509.     return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  510. }
  511.  
  512. static int
  513. list_ass_item(a, i, v)
  514.     PyListObject *a;
  515.     int i;
  516.     PyObject *v;
  517. {
  518.     PyObject *old_value;
  519.     if (i < 0 || i >= a->ob_size) {
  520.         PyErr_SetString(PyExc_IndexError,
  521.                 "list assignment index out of range");
  522.         return -1;
  523.     }
  524.     if (v == NULL)
  525.         return list_ass_slice(a, i, i+1, v);
  526.     Py_INCREF(v);
  527.     old_value = a->ob_item[i];
  528.     a->ob_item[i] = v;
  529.     Py_DECREF(old_value); 
  530.     return 0;
  531. }
  532.  
  533. static PyObject *
  534. ins(self, where, v)
  535.     PyListObject *self;
  536.     int where;
  537.     PyObject *v;
  538. {
  539.     if (ins1(self, where, v) != 0)
  540.         return NULL;
  541.     Py_INCREF(Py_None);
  542.     return Py_None;
  543. }
  544.  
  545. static PyObject *
  546. listinsert(self, args)
  547.     PyListObject *self;
  548.     PyObject *args;
  549. {
  550.     int i;
  551.     PyObject *v;
  552.     if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
  553.         return NULL;
  554.     return ins(self, i, v);
  555. }
  556.  
  557. /* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
  558.  
  559. #ifndef NO_STRICT_LIST_APPEND
  560. #define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
  561. #else
  562. #define PyArg_ParseTuple_Compat1(args, format, ret) \
  563. ( \
  564.     PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
  565.     PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
  566.     PyArg_ParseTuple(args, format, ret) \
  567. )
  568. #endif
  569.  
  570.  
  571. static PyObject *
  572. listappend(self, args)
  573.     PyListObject *self;
  574.     PyObject *args;
  575. {
  576.     PyObject *v;
  577.     if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
  578.         return NULL;
  579.     return ins(self, (int) self->ob_size, v);
  580. }
  581.  
  582. static PyObject *
  583. listextend(self, args)
  584.     PyListObject *self;
  585.     PyObject *args;
  586. {
  587.     PyObject *b = NULL, *res = NULL;
  588.     PyObject **items;
  589.     int selflen = PyList_GET_SIZE(self);
  590.     int blen;
  591.     register int i;
  592.  
  593.     if (!PyArg_ParseTuple(args, "O:extend", &b))
  594.         return NULL;
  595.  
  596.     b = PySequence_Fast(b, "list.extend() argument must be a sequence");
  597.     if (!b)
  598.         return NULL;
  599.  
  600.     if (PyObject_Length(b) == 0)
  601.         /* short circuit when b is empty */
  602.         goto ok;
  603.  
  604.     if (self == (PyListObject*)b) {
  605.         /* as in list_ass_slice() we must special case the
  606.          * situation: a.extend(a)
  607.          *
  608.          * XXX: I think this way ought to be faster than using
  609.          * list_slice() the way list_ass_slice() does.
  610.          */
  611.         Py_DECREF(b);
  612.         b = PyList_New(selflen);
  613.         if (!b)
  614.             return NULL;
  615.         for (i = 0; i < selflen; i++) {
  616.             PyObject *o = PyList_GET_ITEM(self, i);
  617.             Py_INCREF(o);
  618.             PyList_SET_ITEM(b, i, o);
  619.         }
  620.     }
  621.  
  622.     blen = PyObject_Length(b);
  623.  
  624.     /* resize a using idiom */
  625.     items = self->ob_item;
  626.     NRESIZE(items, PyObject*, selflen + blen);
  627.     if (items == NULL) {
  628.         PyErr_NoMemory();
  629.         goto failed;
  630.     }
  631.     self->ob_item = items;
  632.  
  633.     /* populate the end of self with b's items */
  634.     for (i = 0; i < blen; i++) {
  635.         PyObject *o = PySequence_Fast_GET_ITEM(b, i);
  636.         Py_INCREF(o);
  637.         PyList_SET_ITEM(self, self->ob_size++, o);
  638.     }
  639.   ok:
  640.     res = Py_None;
  641.     Py_INCREF(res);
  642.   failed:
  643.     Py_DECREF(b);
  644.     return res;
  645. }
  646.  
  647.  
  648. static PyObject *
  649. listpop(self, args)
  650.     PyListObject *self;
  651.     PyObject *args;
  652. {
  653.     int i = -1;
  654.     PyObject *v;
  655.     if (!PyArg_ParseTuple(args, "|i:pop", &i))
  656.         return NULL;
  657.     if (self->ob_size == 0) {
  658.         /* Special-case most common failure cause */
  659.         PyErr_SetString(PyExc_IndexError, "pop from empty list");
  660.         return NULL;
  661.     }
  662.     if (i < 0)
  663.         i += self->ob_size;
  664.     if (i < 0 || i >= self->ob_size) {
  665.         PyErr_SetString(PyExc_IndexError, "pop index out of range");
  666.         return NULL;
  667.     }
  668.     v = self->ob_item[i];
  669.     Py_INCREF(v);
  670.     if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
  671.         Py_DECREF(v);
  672.         return NULL;
  673.     }
  674.     return v;
  675. }
  676.  
  677. /* New quicksort implementation for arrays of object pointers.
  678.    Thanks to discussions with Tim Peters. */
  679.  
  680. /* CMPERROR is returned by our comparison function when an error
  681.    occurred.  This is the largest negative integer (0x80000000 on a
  682.    32-bit system). */
  683. #define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
  684.  
  685. /* Comparison function.  Takes care of calling a user-supplied
  686.    comparison function (any callable Python object).  Calls the
  687.    standard comparison function, PyObject_Compare(), if the user-
  688.    supplied function is NULL. */
  689.  
  690. static int
  691. docompare(x, y, compare)
  692.     PyObject *x;
  693.     PyObject *y;
  694.     PyObject *compare;
  695. {
  696.     PyObject *args, *res;
  697.     int i;
  698.  
  699.     if (compare == NULL) {
  700.         i = PyObject_Compare(x, y);
  701.         if (i && PyErr_Occurred())
  702.             i = CMPERROR;
  703.         return i;
  704.     }
  705.  
  706.     args = Py_BuildValue("(OO)", x, y);
  707.     if (args == NULL)
  708.         return CMPERROR;
  709.     res = PyEval_CallObject(compare, args);
  710.     Py_DECREF(args);
  711.     if (res == NULL)
  712.         return CMPERROR;
  713.     if (!PyInt_Check(res)) {
  714.         Py_DECREF(res);
  715.         PyErr_SetString(PyExc_TypeError,
  716.                 "comparison function must return int");
  717.         return CMPERROR;
  718.     }
  719.     i = PyInt_AsLong(res);
  720.     Py_DECREF(res);
  721.     if (i < 0)
  722.         return -1;
  723.     if (i > 0)
  724.         return 1;
  725.     return 0;
  726. }
  727.  
  728. /* MINSIZE is the smallest array that will get a full-blown samplesort
  729.    treatment; smaller arrays are sorted using binary insertion.  It must
  730.    be at least 7 for the samplesort implementation to work.  Binary
  731.    insertion does fewer compares, but can suffer O(N**2) data movement.
  732.    The more expensive compares, the larger MINSIZE should be. */
  733. #define MINSIZE 100
  734.  
  735. /* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
  736.    partition; smaller slices are passed to binarysort.  It must be at
  737.    least 2, and no larger than MINSIZE.  Setting it higher reduces the #
  738.    of compares slowly, but increases the amount of data movement quickly.
  739.    The value here was chosen assuming a compare costs ~25x more than
  740.    swapping a pair of memory-resident pointers -- but under that assumption,
  741.    changing the value by a few dozen more or less has aggregate effect
  742.    under 1%.  So the value is crucial, but not touchy <wink>. */
  743. #define MINPARTITIONSIZE 40
  744.  
  745. /* MAXMERGE is the largest number of elements we'll always merge into
  746.    a known-to-be sorted chunk via binary insertion, regardless of the
  747.    size of that chunk.  Given a chunk of N sorted elements, and a group
  748.    of K unknowns, the largest K for which it's better to do insertion
  749.    (than a full-blown sort) is a complicated function of N and K mostly
  750.    involving the expected number of compares and data moves under each
  751.    approach, and the relative cost of those operations on a specific
  752.    architecure.  The fixed value here is conservative, and should be a
  753.    clear win regardless of architecture or N. */
  754. #define MAXMERGE 15
  755.  
  756. /* STACKSIZE is the size of our work stack.  A rough estimate is that
  757.    this allows us to sort arrays of size N where
  758.    N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
  759.    for arrays of size 2**64.  Because we push the biggest partition
  760.    first, the worst case occurs when all subarrays are always partitioned
  761.    exactly in two. */
  762. #define STACKSIZE 60
  763.  
  764.  
  765. #define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
  766.  
  767. /* binarysort is the best method for sorting small arrays: it does
  768.    few compares, but can do data movement quadratic in the number of
  769.    elements.
  770.    [lo, hi) is a contiguous slice of a list, and is sorted via
  771.    binary insertion.
  772.    On entry, must have lo <= start <= hi, and that [lo, start) is already
  773.    sorted (pass start == lo if you don't know!).
  774.    If docompare complains (returns CMPERROR) return -1, else 0.
  775.    Even in case of error, the output slice will be some permutation of
  776.    the input (nothing is lost or duplicated).
  777. */
  778.  
  779. static int
  780. binarysort(lo, hi, start, compare)
  781.     PyObject **lo;
  782.     PyObject **hi;
  783.     PyObject **start;
  784.     PyObject *compare;/* Comparison function object, or NULL for default */
  785. {
  786.     /* assert lo <= start <= hi
  787.        assert [lo, start) is sorted */
  788.     register int k;
  789.     register PyObject **l, **p, **r;
  790.     register PyObject *pivot;
  791.  
  792.     if (lo == start)
  793.         ++start;
  794.     for (; start < hi; ++start) {
  795.         /* set l to where *start belongs */
  796.         l = lo;
  797.         r = start;
  798.         pivot = *r;
  799.         do {
  800.             p = l + ((r - l) >> 1);
  801.             SETK(pivot, *p);
  802.             if (k < 0)
  803.                 r = p;
  804.             else
  805.                 l = p + 1;
  806.         } while (l < r);
  807.         /* Pivot should go at l -- slide over to make room.
  808.            Caution: using memmove is much slower under MSVC 5;
  809.            we're not usually moving many slots. */
  810.         for (p = start; p > l; --p)
  811.             *p = *(p-1);
  812.         *l = pivot;
  813.     }
  814.     return 0;
  815.  
  816.  fail:
  817.     return -1;
  818. }
  819.  
  820. /* samplesortslice is the sorting workhorse.
  821.    [lo, hi) is a contiguous slice of a list, to be sorted in place.
  822.    On entry, must have lo <= hi,
  823.    If docompare complains (returns CMPERROR) return -1, else 0.
  824.    Even in case of error, the output slice will be some permutation of
  825.    the input (nothing is lost or duplicated).
  826.  
  827.    samplesort is basically quicksort on steroids:  a power of 2 close
  828.    to n/ln(n) is computed, and that many elements (less 1) are picked at
  829.    random from the array and sorted.  These 2**k - 1 elements are then
  830.    used as preselected pivots for an equal number of quicksort
  831.    partitioning steps, partitioning the slice into 2**k chunks each of
  832.    size about ln(n).  These small final chunks are then usually handled
  833.    by binarysort.  Note that when k=1, this is roughly the same as an
  834.    ordinary quicksort using a random pivot, and when k=2 this is roughly
  835.    a median-of-3 quicksort.  From that view, using k ~= lg(n/ln(n)) makes
  836.    this a "median of n/ln(n)" quicksort.  You can also view it as a kind
  837.    of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
  838.  
  839.    The large number of samples makes a quadratic-time case almost
  840.    impossible, and asymptotically drives the average-case number of
  841.    compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
  842.    3 variant) down to N lg N.
  843.  
  844.    We also play lots of low-level tricks to cut the number of compares.
  845.    
  846.    Very obscure:  To avoid using extra memory, the PPs are stored in the
  847.    array and shuffled around as partitioning proceeds.  At the start of a
  848.    partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
  849.    adjacent (either on the left or the right!) to a chunk of X elements
  850.    that are to be partitioned: P X or X P.  In either case we need to
  851.    shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
  852.    left, followed by the PP to be used for this step (that's the middle
  853.    of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
  854.        P X or X P -> Psmall pivot X Plarge
  855.    and the order of the PPs must not be altered.  It can take a while
  856.    to realize this isn't trivial!  It can take even longer <wink> to
  857.    understand why the simple code below works, using only 2**(m-1) swaps.
  858.    The key is that the order of the X elements isn't necessarily
  859.    preserved:  X can end up as some cyclic permutation of its original
  860.    order.  That's OK, because X is unsorted anyway.  If the order of X
  861.    had to be preserved too, the simplest method I know of using O(1)
  862.    scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
  863.    Since len(X) is typically several times larger than 2**(m-1), that
  864.    would slow things down.
  865. */
  866.  
  867. struct SamplesortStackNode {
  868.     /* Represents a slice of the array, from (& including) lo up
  869.        to (but excluding) hi.  "extra" additional & adjacent elements
  870.        are pre-selected pivots (PPs), spanning [lo-extra, lo) if
  871.        extra > 0, or [hi, hi-extra) if extra < 0.  The PPs are
  872.        already sorted, but nothing is known about the other elements
  873.        in [lo, hi). |extra| is always one less than a power of 2.
  874.        When extra is 0, we're out of PPs, and the slice must be
  875.        sorted by some other means. */
  876.     PyObject **lo;
  877.     PyObject **hi;
  878.     int extra;
  879. };
  880.  
  881. /* The number of PPs we want is 2**k - 1, where 2**k is as close to
  882.    N / ln(N) as possible.  So k ~= lg(N / ln(N)).  Calling libm routines
  883.    is undesirable, so cutoff values are canned in the "cutoff" table
  884.    below:  cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
  885. #define CUTOFFBASE 4
  886. static long cutoff[] = {
  887.     43,        /* smallest N such that k == 4 */
  888.     106,       /* etc */
  889.     250,
  890.     576,
  891.     1298,
  892.     2885,
  893.     6339,
  894.     13805,
  895.     29843,
  896.     64116,
  897.     137030,
  898.     291554,
  899.     617916,
  900.     1305130,
  901.     2748295,
  902.     5771662,
  903.     12091672,
  904.     25276798,
  905.     52734615,
  906.     109820537,
  907.     228324027,
  908.     473977813,
  909.     982548444,   /* smallest N such that k == 26 */
  910.     2034159050   /* largest N that fits in signed 32-bit; k == 27 */
  911. };
  912.  
  913. static int
  914. samplesortslice(lo, hi, compare)
  915.     PyObject **lo;
  916.     PyObject **hi;
  917.     PyObject *compare;/* Comparison function object, or NULL for default */
  918. {
  919.     register PyObject **l, **r;
  920.     register PyObject *tmp, *pivot;
  921.     register int k;
  922.     int n, extra, top, extraOnRight;
  923.     struct SamplesortStackNode stack[STACKSIZE];
  924.  
  925.     /* assert lo <= hi */
  926.     n = hi - lo;
  927.  
  928.     /* ----------------------------------------------------------
  929.      * Special cases
  930.      * --------------------------------------------------------*/
  931.     if (n < 2)
  932.         return 0;
  933.  
  934.     /* Set r to the largest value such that [lo,r) is sorted.
  935.        This catches the already-sorted case, the all-the-same
  936.        case, and the appended-a-few-elements-to-a-sorted-list case.
  937.        If the array is unsorted, we're very likely to get out of
  938.        the loop fast, so the test is cheap if it doesn't pay off.
  939.     */
  940.     /* assert lo < hi */
  941.     for (r = lo+1; r < hi; ++r) {
  942.         SETK(*r, *(r-1));
  943.         if (k < 0)
  944.             break;
  945.     }
  946.     /* [lo,r) is sorted, [r,hi) unknown.  Get out cheap if there are
  947.        few unknowns, or few elements in total. */
  948.     if (hi - r <= MAXMERGE || n < MINSIZE)
  949.         return binarysort(lo, hi, r, compare);
  950.  
  951.     /* Check for the array already being reverse-sorted.  Typical
  952.        benchmark-driven silliness <wink>. */
  953.     /* assert lo < hi */
  954.     for (r = lo+1; r < hi; ++r) {
  955.         SETK(*(r-1), *r);
  956.         if (k < 0)
  957.             break;
  958.     }
  959.     if (hi - r <= MAXMERGE) {
  960.         /* Reverse the reversed prefix, then insert the tail */
  961.         PyObject **originalr = r;
  962.         l = lo;
  963.         do {
  964.             --r;
  965.             tmp = *l; *l = *r; *r = tmp;
  966.             ++l;
  967.         } while (l < r);
  968.         return binarysort(lo, hi, originalr, compare);
  969.     }
  970.  
  971.     /* ----------------------------------------------------------
  972.      * Normal case setup: a large array without obvious pattern.
  973.      * --------------------------------------------------------*/
  974.  
  975.     /* extra := a power of 2 ~= n/ln(n), less 1.
  976.        First find the smallest extra s.t. n < cutoff[extra] */
  977.     for (extra = 0;
  978.          extra < sizeof(cutoff) / sizeof(cutoff[0]);
  979.          ++extra) {
  980.         if (n < cutoff[extra])
  981.             break;
  982.         /* note that if we fall out of the loop, the value of
  983.            extra still makes *sense*, but may be smaller than
  984.            we would like (but the array has more than ~= 2**31
  985.            elements in this case!) */ 
  986.     }
  987.     /* Now k == extra - 1 + CUTOFFBASE.  The smallest value k can
  988.        have is CUTOFFBASE-1, so
  989.        assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
  990.     extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
  991.     /* assert extra > 0 and n >= extra */
  992.  
  993.     /* Swap that many values to the start of the array.  The
  994.        selection of elements is pseudo-random, but the same on
  995.        every run (this is intentional! timing algorithm changes is
  996.        a pain if timing varies across runs).  */
  997.     {
  998.         unsigned int seed = n / extra;  /* arbitrary */
  999.         unsigned int i;
  1000.         for (i = 0; i < (unsigned)extra; ++i) {
  1001.             /* j := random int in [i, n) */
  1002.             unsigned int j;
  1003.             seed = seed * 69069 + 7;
  1004.             j = i + seed % (n - i);
  1005.             tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
  1006.         }
  1007.     }
  1008.  
  1009.     /* Recursively sort the preselected pivots. */
  1010.     if (samplesortslice(lo, lo + extra, compare) < 0)
  1011.         goto fail;
  1012.  
  1013.     top = 0;          /* index of available stack slot */
  1014.     lo += extra;      /* point to first unknown */
  1015.     extraOnRight = 0; /* the PPs are at the left end */
  1016.  
  1017.     /* ----------------------------------------------------------
  1018.      * Partition [lo, hi), and repeat until out of work.
  1019.      * --------------------------------------------------------*/
  1020.     for (;;) {
  1021.         /* assert lo <= hi, so n >= 0 */
  1022.         n = hi - lo;
  1023.  
  1024.         /* We may not want, or may not be able, to partition:
  1025.            If n is small, it's quicker to insert.
  1026.            If extra is 0, we're out of pivots, and *must* use
  1027.            another method.
  1028.         */
  1029.         if (n < MINPARTITIONSIZE || extra == 0) {
  1030.             if (n >= MINSIZE) {
  1031.                 /* assert extra == 0
  1032.                    This is rare, since the average size
  1033.                    of a final block is only about
  1034.                    ln(original n). */
  1035.                 if (samplesortslice(lo, hi, compare) < 0)
  1036.                     goto fail;
  1037.             }
  1038.             else {
  1039.                 /* Binary insertion should be quicker,
  1040.                    and we can take advantage of the PPs
  1041.                    already being sorted. */
  1042.                 if (extraOnRight && extra) {
  1043.                     /* swap the PPs to the left end */
  1044.                     k = extra;
  1045.                     do {
  1046.                         tmp = *lo;
  1047.                         *lo = *hi;
  1048.                         *hi = tmp;
  1049.                         ++lo; ++hi;
  1050.                     } while (--k);
  1051.                 }
  1052.                 if (binarysort(lo - extra, hi, lo,
  1053.                            compare) < 0)
  1054.                     goto fail;
  1055.             }
  1056.  
  1057.             /* Find another slice to work on. */
  1058.             if (--top < 0)
  1059.                 break;   /* no more -- done! */
  1060.             lo = stack[top].lo;
  1061.             hi = stack[top].hi;
  1062.             extra = stack[top].extra;
  1063.             extraOnRight = 0;
  1064.             if (extra < 0) {
  1065.                 extraOnRight = 1;
  1066.                 extra = -extra;
  1067.             }
  1068.             continue;
  1069.         }
  1070.  
  1071.         /* Pretend the PPs are indexed 0, 1, ..., extra-1.
  1072.            Then our preselected pivot is at (extra-1)/2, and we
  1073.            want to move the PPs before that to the left end of
  1074.            the slice, and the PPs after that to the right end.
  1075.            The following section changes extra, lo, hi, and the
  1076.            slice such that:
  1077.            [lo-extra, lo) contains the smaller PPs.
  1078.            *lo == our PP.
  1079.            (lo, hi) contains the unknown elements.
  1080.            [hi, hi+extra) contains the larger PPs.
  1081.         */
  1082.         k = extra >>= 1;  /* num PPs to move */ 
  1083.         if (extraOnRight) {
  1084.             /* Swap the smaller PPs to the left end.
  1085.                Note that this loop actually moves k+1 items:
  1086.                the last is our PP */
  1087.             do {
  1088.                 tmp = *lo; *lo = *hi; *hi = tmp;
  1089.                 ++lo; ++hi;
  1090.             } while (k--);
  1091.         }
  1092.         else {
  1093.             /* Swap the larger PPs to the right end. */
  1094.             while (k--) {
  1095.                 --lo; --hi;
  1096.                 tmp = *lo; *lo = *hi; *hi = tmp;
  1097.             }
  1098.         }
  1099.         --lo;   /* *lo is now our PP */
  1100.         pivot = *lo;
  1101.  
  1102.         /* Now an almost-ordinary quicksort partition step.
  1103.            Note that most of the time is spent here!
  1104.            Only odd thing is that we partition into < and >=,
  1105.            instead of the usual <= and >=.  This helps when
  1106.            there are lots of duplicates of different values,
  1107.            because it eventually tends to make subfiles
  1108.            "pure" (all duplicates), and we special-case for
  1109.            duplicates later. */
  1110.         l = lo + 1;
  1111.         r = hi - 1;
  1112.         /* assert lo < l < r < hi (small n weeded out above) */
  1113.  
  1114.         do {
  1115.             /* slide l right, looking for key >= pivot */
  1116.             do {
  1117.                 SETK(*l, pivot);
  1118.                 if (k < 0)
  1119.                     ++l;
  1120.                 else
  1121.                     break;
  1122.             } while (l < r);
  1123.  
  1124.             /* slide r left, looking for key < pivot */
  1125.             while (l < r) {
  1126.                 register PyObject *rval = *r--;
  1127.                 SETK(rval, pivot);
  1128.                 if (k < 0) {
  1129.                     /* swap and advance */
  1130.                     r[1] = *l;
  1131.                     *l++ = rval;
  1132.                     break;
  1133.                 }
  1134.             }
  1135.  
  1136.         } while (l < r);
  1137.  
  1138.         /* assert lo < r <= l < hi
  1139.            assert r == l or r+1 == l
  1140.            everything to the left of l is < pivot, and
  1141.            everything to the right of r is >= pivot */
  1142.  
  1143.         if (l == r) {
  1144.             SETK(*r, pivot);
  1145.             if (k < 0)
  1146.                 ++l;
  1147.             else
  1148.                 --r;
  1149.         }
  1150.         /* assert lo <= r and r+1 == l and l <= hi
  1151.            assert r == lo or a[r] < pivot
  1152.            assert a[lo] is pivot
  1153.            assert l == hi or a[l] >= pivot
  1154.            Swap the pivot into "the middle", so we can henceforth
  1155.            ignore it.
  1156.         */
  1157.         *lo = *r;
  1158.         *r = pivot;
  1159.  
  1160.         /* The following is true now, & will be preserved:
  1161.            All in [lo,r) are < pivot
  1162.            All in [r,l) == pivot (& so can be ignored)
  1163.            All in [l,hi) are >= pivot */
  1164.  
  1165.         /* Check for duplicates of the pivot.  One compare is
  1166.            wasted if there are no duplicates, but can win big
  1167.            when there are.
  1168.            Tricky: we're sticking to "<" compares, so deduce
  1169.            equality indirectly.  We know pivot <= *l, so they're
  1170.            equal iff not pivot < *l.
  1171.         */
  1172.         while (l < hi) {
  1173.             /* pivot <= *l known */
  1174.             SETK(pivot, *l);
  1175.             if (k < 0)
  1176.                 break;
  1177.             else
  1178.                 /* <= and not < implies == */
  1179.                 ++l;
  1180.         }
  1181.  
  1182.         /* assert lo <= r < l <= hi
  1183.            Partitions are [lo, r) and [l, hi) */
  1184.  
  1185.         /* push fattest first; remember we still have extra PPs
  1186.            to the left of the left chunk and to the right of
  1187.            the right chunk! */
  1188.         /* assert top < STACKSIZE */
  1189.         if (r - lo <= hi - l) {
  1190.             /* second is bigger */
  1191.             stack[top].lo = l;
  1192.             stack[top].hi = hi;
  1193.             stack[top].extra = -extra;
  1194.             hi = r;
  1195.             extraOnRight = 0;
  1196.         }
  1197.         else {
  1198.             /* first is bigger */
  1199.             stack[top].lo = lo;
  1200.             stack[top].hi = r;
  1201.             stack[top].extra = extra;
  1202.             lo = l;
  1203.             extraOnRight = 1;
  1204.         }
  1205.         ++top;
  1206.  
  1207.     }   /* end of partitioning loop */
  1208.  
  1209.     return 0;
  1210.  
  1211.  fail:
  1212.     return -1;
  1213. }
  1214.  
  1215. #undef SETK
  1216.  
  1217. staticforward PyTypeObject immutable_list_type;
  1218.  
  1219. static PyObject *
  1220. listsort(self, args)
  1221.     PyListObject *self;
  1222.     PyObject *args;
  1223. {
  1224.     int err;
  1225.     PyObject *compare = NULL;
  1226.  
  1227.     if (args != NULL) {
  1228.         if (!PyArg_ParseTuple(args, "|O:sort", &compare))
  1229.             return NULL;
  1230.     }
  1231.     self->ob_type = &immutable_list_type;
  1232.     err = samplesortslice(self->ob_item,
  1233.                   self->ob_item + self->ob_size,
  1234.                   compare);
  1235.     self->ob_type = &PyList_Type;
  1236.     if (err < 0)
  1237.         return NULL;
  1238.     Py_INCREF(Py_None);
  1239.     return Py_None;
  1240. }
  1241.  
  1242. int
  1243. PyList_Sort(v)
  1244.     PyObject *v;
  1245. {
  1246.     if (v == NULL || !PyList_Check(v)) {
  1247.         PyErr_BadInternalCall();
  1248.         return -1;
  1249.     }
  1250.     v = listsort((PyListObject *)v, (PyObject *)NULL);
  1251.     if (v == NULL)
  1252.         return -1;
  1253.     Py_DECREF(v);
  1254.     return 0;
  1255. }
  1256.  
  1257. static PyObject *
  1258. listreverse(self, args)
  1259.     PyListObject *self;
  1260.     PyObject *args;
  1261. {
  1262.     register PyObject **p, **q;
  1263.     register PyObject *tmp;
  1264.     
  1265.     if (!PyArg_ParseTuple(args, ":reverse"))
  1266.         return NULL;
  1267.  
  1268.     if (self->ob_size > 1) {
  1269.         for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
  1270.                         p < q; p++, q--) {
  1271.             tmp = *p;
  1272.             *p = *q;
  1273.             *q = tmp;
  1274.         }
  1275.     }
  1276.     
  1277.     Py_INCREF(Py_None);
  1278.     return Py_None;
  1279. }
  1280.  
  1281. int
  1282. PyList_Reverse(v)
  1283.     PyObject *v;
  1284. {
  1285.     if (v == NULL || !PyList_Check(v)) {
  1286.         PyErr_BadInternalCall();
  1287.         return -1;
  1288.     }
  1289.     v = listreverse((PyListObject *)v, (PyObject *)NULL);
  1290.     if (v == NULL)
  1291.         return -1;
  1292.     Py_DECREF(v);
  1293.     return 0;
  1294. }
  1295.  
  1296. PyObject *
  1297. PyList_AsTuple(v)
  1298.     PyObject *v;
  1299. {
  1300.     PyObject *w;
  1301.     PyObject **p;
  1302.     int n;
  1303.     if (v == NULL || !PyList_Check(v)) {
  1304.         PyErr_BadInternalCall();
  1305.         return NULL;
  1306.     }
  1307.     n = ((PyListObject *)v)->ob_size;
  1308.     w = PyTuple_New(n);
  1309.     if (w == NULL)
  1310.         return NULL;
  1311.     p = ((PyTupleObject *)w)->ob_item;
  1312.     memcpy((ANY *)p,
  1313.            (ANY *)((PyListObject *)v)->ob_item,
  1314.            n*sizeof(PyObject *));
  1315.     while (--n >= 0) {
  1316.         Py_INCREF(*p);
  1317.         p++;
  1318.     }
  1319.     return w;
  1320. }
  1321.  
  1322. static PyObject *
  1323. listindex(self, args)
  1324.     PyListObject *self;
  1325.     PyObject *args;
  1326. {
  1327.     int i;
  1328.     PyObject *v;
  1329.  
  1330.     if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
  1331.         return NULL;
  1332.     for (i = 0; i < self->ob_size; i++) {
  1333.         if (PyObject_Compare(self->ob_item[i], v) == 0)
  1334.             return PyInt_FromLong((long)i);
  1335.         if (PyErr_Occurred())
  1336.             return NULL;
  1337.     }
  1338.     PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
  1339.     return NULL;
  1340. }
  1341.  
  1342. static PyObject *
  1343. listcount(self, args)
  1344.     PyListObject *self;
  1345.     PyObject *args;
  1346. {
  1347.     int count = 0;
  1348.     int i;
  1349.     PyObject *v;
  1350.  
  1351.     if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
  1352.         return NULL;
  1353.     for (i = 0; i < self->ob_size; i++) {
  1354.         if (PyObject_Compare(self->ob_item[i], v) == 0)
  1355.             count++;
  1356.         if (PyErr_Occurred())
  1357.             return NULL;
  1358.     }
  1359.     return PyInt_FromLong((long)count);
  1360. }
  1361.  
  1362. static PyObject *
  1363. listremove(self, args)
  1364.     PyListObject *self;
  1365.     PyObject *args;
  1366. {
  1367.     int i;
  1368.     PyObject *v;
  1369.  
  1370.     if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
  1371.         return NULL;
  1372.     for (i = 0; i < self->ob_size; i++) {
  1373.         if (PyObject_Compare(self->ob_item[i], v) == 0) {
  1374.             if (list_ass_slice(self, i, i+1,
  1375.                        (PyObject *)NULL) != 0)
  1376.                 return NULL;
  1377.             Py_INCREF(Py_None);
  1378.             return Py_None;
  1379.         }
  1380.         if (PyErr_Occurred())
  1381.             return NULL;
  1382.     }
  1383.     PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
  1384.     return NULL;
  1385. }
  1386.  
  1387. static char append_doc[] =
  1388. "L.append(object) -- append object to end";
  1389. static char extend_doc[] =
  1390. "L.extend(list) -- extend list by appending list elements";
  1391. static char insert_doc[] =
  1392. "L.insert(index, object) -- insert object before index";
  1393. static char pop_doc[] =
  1394. "L.pop([index]) -> item -- remove and return item at index (default last)";
  1395. static char remove_doc[] =
  1396. "L.remove(value) -- remove first occurrence of value";
  1397. static char index_doc[] =
  1398. "L.index(value) -> integer -- return index of first occurrence of value";
  1399. static char count_doc[] =
  1400. "L.count(value) -> integer -- return number of occurrences of value";
  1401. static char reverse_doc[] =
  1402. "L.reverse() -- reverse *IN PLACE*";
  1403. static char sort_doc[] =
  1404. "L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
  1405.  
  1406. static PyMethodDef list_methods[] = {
  1407.     {"append",    (PyCFunction)listappend, 1, append_doc},
  1408.     {"insert",    (PyCFunction)listinsert, 1, insert_doc},
  1409.     {"extend",      (PyCFunction)listextend, 1, extend_doc},
  1410.     {"pop",        (PyCFunction)listpop, 1, pop_doc},
  1411.     {"remove",    (PyCFunction)listremove, 1, remove_doc},
  1412.     {"index",    (PyCFunction)listindex, 1, index_doc},
  1413.     {"count",    (PyCFunction)listcount, 1, count_doc},
  1414.     {"reverse",    (PyCFunction)listreverse, 1, reverse_doc},
  1415.     {"sort",    (PyCFunction)listsort, 1, sort_doc},
  1416.     {NULL,        NULL}        /* sentinel */
  1417. };
  1418.  
  1419. static PyObject *
  1420. list_getattr(f, name)
  1421.     PyListObject *f;
  1422.     char *name;
  1423. {
  1424.     return Py_FindMethod(list_methods, (PyObject *)f, name);
  1425. }
  1426.  
  1427. static PySequenceMethods list_as_sequence = {
  1428.     (inquiry)list_length, /*sq_length*/
  1429.     (binaryfunc)list_concat, /*sq_concat*/
  1430.     (intargfunc)list_repeat, /*sq_repeat*/
  1431.     (intargfunc)list_item, /*sq_item*/
  1432.     (intintargfunc)list_slice, /*sq_slice*/
  1433.     (intobjargproc)list_ass_item, /*sq_ass_item*/
  1434.     (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
  1435.     (objobjproc)list_contains, /*sq_contains*/
  1436. };
  1437.  
  1438. PyTypeObject PyList_Type = {
  1439.     PyObject_HEAD_INIT(&PyType_Type)
  1440.     0,
  1441.     "list",
  1442.     sizeof(PyListObject),
  1443.     0,
  1444.     (destructor)list_dealloc, /*tp_dealloc*/
  1445.     (printfunc)list_print, /*tp_print*/
  1446.     (getattrfunc)list_getattr, /*tp_getattr*/
  1447.     0,        /*tp_setattr*/
  1448.     (cmpfunc)list_compare, /*tp_compare*/
  1449.     (reprfunc)list_repr, /*tp_repr*/
  1450.     0,        /*tp_as_number*/
  1451.     &list_as_sequence,    /*tp_as_sequence*/
  1452.     0,        /*tp_as_mapping*/
  1453. };
  1454.  
  1455.  
  1456. /* During a sort, we really can't have anyone modifying the list; it could
  1457.    cause core dumps.  Thus, we substitute a dummy type that raises an
  1458.    explanatory exception when a modifying operation is used.  Caveat:
  1459.    comparisons may behave differently; but I guess it's a bad idea anyway to
  1460.    compare a list that's being sorted... */
  1461.  
  1462. static PyObject *
  1463. immutable_list_op(/*No args!*/)
  1464. {
  1465.     PyErr_SetString(PyExc_TypeError,
  1466.             "a list cannot be modified while it is being sorted");
  1467.     return NULL;
  1468. }
  1469.  
  1470. static PyMethodDef immutable_list_methods[] = {
  1471.     {"append",    (PyCFunction)immutable_list_op},
  1472.     {"insert",    (PyCFunction)immutable_list_op},
  1473.     {"remove",    (PyCFunction)immutable_list_op},
  1474.     {"index",    (PyCFunction)listindex},
  1475.     {"count",    (PyCFunction)listcount},
  1476.     {"reverse",    (PyCFunction)immutable_list_op},
  1477.     {"sort",    (PyCFunction)immutable_list_op},
  1478.     {NULL,        NULL}        /* sentinel */
  1479. };
  1480.  
  1481. static PyObject *
  1482. immutable_list_getattr(f, name)
  1483.     PyListObject *f;
  1484.     char *name;
  1485. {
  1486.     return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
  1487. }
  1488.  
  1489. static int
  1490. immutable_list_ass(/*No args!*/)
  1491. {
  1492.     immutable_list_op();
  1493.     return -1;
  1494. }
  1495.  
  1496. static PySequenceMethods immutable_list_as_sequence = {
  1497.     (inquiry)list_length, /*sq_length*/
  1498.     (binaryfunc)list_concat, /*sq_concat*/
  1499.     (intargfunc)list_repeat, /*sq_repeat*/
  1500.     (intargfunc)list_item, /*sq_item*/
  1501.     (intintargfunc)list_slice, /*sq_slice*/
  1502.     (intobjargproc)immutable_list_ass, /*sq_ass_item*/
  1503.     (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
  1504. };
  1505.  
  1506. static PyTypeObject immutable_list_type = {
  1507.     PyObject_HEAD_INIT(&PyType_Type)
  1508.     0,
  1509.     "list (immutable, during sort)",
  1510.     sizeof(PyListObject),
  1511.     0,
  1512.     0,        /*tp_dealloc*/ /* Cannot happen */
  1513.     (printfunc)list_print, /*tp_print*/
  1514.     (getattrfunc)immutable_list_getattr, /*tp_getattr*/
  1515.     0,        /*tp_setattr*/
  1516.     0,        /*tp_compare*/ /* Won't be called */
  1517.     (reprfunc)list_repr, /*tp_repr*/
  1518.     0,        /*tp_as_number*/
  1519.     &immutable_list_as_sequence,    /*tp_as_sequence*/
  1520.     0,        /*tp_as_mapping*/
  1521. };
  1522.  
  1523.